package com.demoo.zjsu.util.HttpClientUtil;

import com.demoo.zjsu.string.BaseStrings;
import com.demoo.zjsu.string.JSONstrings;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by jshjsh on 2016/8/15.
 * httpclient实现下载图片
 */
@Component
public class ClientImgDownloader implements ClientSender{

//    @Resource(name = "requestConfig")
//    RequestConfig config;

    Logger logger = Logger.getLogger(getClass());

    private String filename;

    private String path;

    public ClientImgDownloader() {

    }

    public ClientImgDownloader(String filename, String path) {
        this.filename = filename;
        this.path = path;
    }

    public HttpRequestBase getRequest(String url) {
        HttpGet get = new HttpGet(url);
//        get.setConfig(config);
        return get;
    }

    public  String getEntity(CloseableHttpResponse response) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            FileOutputStream os = null;
            try {
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                os = new FileOutputStream(path+filename);
                InputStream is = entity.getContent();
                IOUtils.copy(is, os);
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return JSONstrings.SUCCESS;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
